package com.qubuyer.business.mine.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.alipay.sdk.app.AuthTask
import com.qubuyer.R
import com.qubuyer.bean.payment.AliPayAuthResultEntity
import com.qubuyer.business.mine.viewmodel.UserViewModel
import com.qubuyer.constant.AppConstant
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.core.ext.application
import com.qubuyer.databinding.FragmentThirdAccountBinding
import com.qubuyer.events.WeChatAuthEvent
import com.qubuyer.utils.SessionUtil
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.Subscribe

/**
 * @author Susong
 * @date 创建时间:2019/4/12
 * @description 第三方账户activity
 * & @version
 */
class ThirdAccountFragment : MVVMFragment<FragmentThirdAccountBinding, UserViewModel>() {

    private val wxApi: Lazy<IWXAPI> = lazy {
        WXAPIFactory.createWXAPI(application, AppConstant.WECHAT_APP_ID, false).also {
            it.registerApp(AppConstant.WECHAT_APP_ID)
        }
    }

    override fun getTitle(): String {
        return "第三方账户"
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.userEntity.observe(viewLifecycleOwner, {
            if (it.is_bind_wx == 1) {
                viewDataBinding.rlWechatAccount.isEnabled = false
                viewDataBinding.tvWechatAccount.text = "已绑定"
            } else {
                viewDataBinding.rlWechatAccount.isEnabled = true
                viewDataBinding.tvWechatAccount.text = "未绑定"
            }
            if (it.is_bind_alipay == 1) {
                viewDataBinding.rlAlipayAccount.isEnabled = false
                viewDataBinding.tvAlipayAccount.text = "已绑定"
            } else {
                viewDataBinding.rlAlipayAccount.isEnabled = true
                viewDataBinding.tvAlipayAccount.text = "未绑定"
            }
        })
        viewModel.getUserInfo()
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.rl_wechat_account -> {
                val req = SendAuth.Req()
                req.scope = "snsapi_userinfo"
                req.state = "snsapi_login_lnint"
                wxApi.value.sendReq(req)
            }
            R.id.rl_alipay_account -> getAliPayParams()
        }
    }

    private fun getAliPayParams() {
        viewModel.getAliPayParams { params ->
            launch {
                val authResult = withContext(Dispatchers.IO) {
                    AliPayAuthResultEntity(AuthTask(mContext).authV2(params, true), true)
                }
                val resultStatus = authResult.resultStatus
                // 判断resultStatus 为“9000”且result_code为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.resultCode, "200")) {
                    viewModel.bindThirdAccount("alipay", authResult.alipayOpenId) {
                        val entity = SessionUtil.getInstance().userInfo
                        entity.is_bind_alipay = 1
                        SessionUtil.getInstance().saveUserInfo(entity)
                        toast("绑定成功")
                        mContext.onBackPressed()
                    }
                } else {
                    // 其他状态值则为授权失败
                    toast(authResult.memo)
                }
            }
        }
    }

    override fun onDataBinding(dataBinding: FragmentThirdAccountBinding) {
        dataBinding.host = this
    }

    override val viewModel: UserViewModel by injectVMByActivity()
    override val layoutId: Int
        get() = R.layout.fragment_third_account

    @Subscribe
    fun onEvent(event: WeChatAuthEvent) {
        viewModel.bindThirdAccount("wx", event.openId) {
            val entity = SessionUtil.getInstance().userInfo
            entity.is_bind_wx = 1
            SessionUtil.getInstance().saveUserInfo(entity)
            toast("绑定成功")
            mContext.onBackPressed()
        }
    }
}